/*
 * Connection.cpp
 *
 *  Created on: 2009-02-12
 *      Author: ck
 */

#include "ConnectionPlayer.h"

ConnectionPlayer::ConnectionPlayer(QObject * parent) : QTcpSocket(parent) {
	blockSize = 0;
	id=-1;
	setReady(false);
	setSitting(false);
	connect(this, SIGNAL (readyRead()), this, SLOT (readMessage()));
	connect(this, SIGNAL (bytesWritten(qint64)), this, SLOT (readMessage()));
	//connect(this, SIGNAL (stateChanged ( QAbstractSocket::SocketState )), this, SLOT (onStateChange(QAbstractSocket::SocketState)));
	connect(this, SIGNAL(disconnected()), this, SLOT (onDisconnected()));
}

void ConnectionPlayer::readMessage() {
	QDataStream in(this);
	in.setVersion(QDataStream::Qt_4_3);
	if (blockSize == 0) {
		if (bytesAvailable() < (int)sizeof(quint16))
			return;
		in >> blockSize;
	}
	//static int licz = 0;
	if (bytesAvailable() < blockSize)
		return;
	QString msg;
	in >> msg;
	int cmdLen = msg.indexOf(" ");
	QString cmd = msg.left(cmdLen);//cmd to komenda string np. NICK <nick>, wszystko oddzielone spacjami, jak w tym zadaniu od Klisa
	QString argStr = msg.mid(cmdLen+1);
	QStringList args = argStr.split(" ");

	blockSize = 0;
	emit newMessage(this, cmd, args);
	if (!atEnd())
		readMessage();
}

void ConnectionPlayer::sendMessage(QString cmd, QStringList args) {
	QString message;
	message += cmd;
	if (args.size() > 0) message += " " + args.join(" ");
	QByteArray block;
	QDataStream out(&block, QIODevice::ReadWrite);
	out.setVersion(QDataStream::Qt_4_3);
	out << (quint16)0;
	out << message;
	out.device()->seek(0);
	out << (quint16)(block.size() - sizeof(quint16));
	write(block);
}

void ConnectionPlayer::resetData() {
	setNick("");
	setId(-1);
	setReady(false);
	setSitting(false);
}

void ConnectionPlayer::onDisconnected() {
	emit socketDisconnected(this);
}

ConnectionPlayer::~ConnectionPlayer() {
	// TODO Auto-generated destructor stub
}
